﻿using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WH.Contracts.Select;
using WH.Contracts.Systems.Menus;
using WH.Contracts.Systems.RolePermissions;
using WH.Contracts.Systems.Roles;
using WH.Model.Systems;
using WH.Services.IServices.ISystem;
using Rw.Core.Common;
using Rw.Core.Common.Extensions;
using Rw.Core.Common.Paging;
using WH.Common.Constant;
using WH.Common.Helper;
using WH.Common.Paging;
using WH.Common.UniOfWork;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace WH.WebApi.Controllers.Systems
{
    /// <summary>
    /// 角色信息说明表接口
    /// </summary>
    [Authorize, Route("Roles"), ApiController]
    public class RolesController : BaseController
    {
        private readonly IRoleService _roleService;
        private readonly IMenuService _menuService;
        private readonly IRolePermissionService _rolePermissionService;
        private readonly IOrganizationService _organizationService;
        private readonly IKeyValueService _keyValueService;
        private readonly IUnitOfWork _unitOfWork;

        /// <summary>
        /// 角色
        /// </summary>
        public RolesController(IRoleService roleService,
                                    IMenuService menuService,
                                    IRolePermissionService rolePermissionService,
                                    IOrganizationService organizationService,
                                    IKeyValueService keyValueService,
                                    IUnitOfWork unitOfWork)
        {
            _keyValueService = keyValueService;
            _roleService = roleService;
            _rolePermissionService = rolePermissionService;
            _organizationService = organizationService;
            _menuService = menuService;
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 根据角色id获取角色
        /// </summary>
        /// <param name="id">角色Id</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ResultResponse<RoleOutputDto>> GetRoleByIdAsync(string id)
        {
            var role = await _roleService.FindByIdAsync(id);

            if (role is null)
            {
                return Error<RoleOutputDto>("未查找到该角色，请重新操作");
            }

            var data = new RoleOutputDto
            {
                Id = role.Id,
                Code = role.Code,
                Name = role.Name,
                TypeCode = role.TypeCode,
                TypeCodeString = role.RoleType?.Name,
                Description = role.Description,
                SortCode = role.SortCode,
                IsEnable = role.IsEnable,
                OrganizationId = role.OrganizationId,
                Remark = role.Remark,
            };

            return Success(data);
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task<ResultResponse> PostAsync([FromBody] RoleInputDto input)
        {
            var exist = await _roleService.ExistsAsync(a => a.Code == input.Code);
            if (exist)
            {
                return Error("请确保角色编号唯一，请重新操作");
            }

            var role = new RoleEntity
            {
                Id = Snowflake.GetNewId(),
                Code = input.Code,
                Name = input.Name,
                Description = input.Description,
                TypeCode = input.TypeCode,
                SortCode = input.SortCode,
                IsEnable = input.IsEnable,
                Remark = input.Remark,
                //Type = RoleTypeEnum.User,
                OrganizationId = input.OrganizationId,
            };

            var res = await _roleService.CreateAsync(role);

            if (input.ResourceIds is not null)
            {
                var menus = await _menuService.FindAllAsync(m => input.ResourceIds.Contains(m.Id));//role.OrganizationId == m.OrganizationId &&
                var rolePermissions = new List<RolePermissionEntity>();
                foreach (var menu in menus)
                {
                    var rolePermission = new RolePermissionEntity
                    {
                        Id = Snowflake.GetNewId(),
                        RoleType = 1,
                        RoleId = role.Id,
                        ResourceId = menu.Id,
                        ResourceType = menu.MenuType,
                        OrganizationId = role.OrganizationId,
                        IsEnable = true,
                    };
                    rolePermissions.Add(rolePermission);
                }

                var t = new List<int?> { BusinessFunction.rt_0, BusinessFunction.rt_1, BusinessFunction.rt_2, BusinessFunction.rt_3, };
                await _rolePermissionService.RemoveAsync(rp => rp.RoleId == role.Id && t.Contains(rp.ResourceType));
                if (rolePermissions.Any())
                {
                    await _rolePermissionService.CreateAsync(rolePermissions);
                }
            }

            return res > 0 ? Success() : Error();
        }

        /// <summary>
        /// 菜单权限
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("Resource")]
        public async Task<ResultResponse> PutResourceIdsAsync([FromBody] RoleIdsDto input)
        {
            try
            {
                await _unitOfWork.BeginTranAsync();

                var role = await _roleService.FirstOrDefaultAsync(x => x.Id == input.RoleId);
                if (role is null)
                {
                    return Error("角色不存在，请检查");
                }

                if (input.ResourceIds is not null)
                {
                    var menus = await _menuService.FindAllAsync(m => input.ResourceIds.Contains(m.Id));//role.OrganizationId == m.OrganizationId &&
                    var rolePermissions = new List<RolePermissionEntity>();
                    foreach (var menu in menus)
                    {
                        var rolePermission = new RolePermissionEntity
                        {
                            Id = Snowflake.GetNewId(),
                            RoleType = 1,
                            RoleId = role.Id,
                            ResourceId = menu.Id,
                            ResourceType = menu.MenuType,
                            OrganizationId = role.OrganizationId,
                            IsEnable = true,
                        };
                        rolePermissions.Add(rolePermission);
                    }

                    var t = new List<int?> { BusinessFunction.rt_0, BusinessFunction.rt_1, BusinessFunction.rt_2, BusinessFunction.rt_3 };
                    await _rolePermissionService.RemoveAsync(rp => rp.RoleId == role.Id && t.Contains(rp.ResourceType));
                    if (rolePermissions.Any())
                    {
                        await _rolePermissionService.CreateAsync(rolePermissions);
                    }
                }
                await _unitOfWork.CommitTranAsync();

                return Success();
            }
            catch (Exception)
            {
                await _unitOfWork.RollbackTranAsync();

                throw;
            }
        }

        ///// <summary>
        ///// 病区权限
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPut("wards")]
        //public async Task<ResultResponse> PutWardsAsync([FromBody] RoleIdsDto input)
        //{
        //    try
        //    {
        //        _unitOfWork.BeginTran();

        //        var role = _roleService.FirstOrDefault(x => x.Id == input.RoleId);
        //        if (role is null)
        //        {
        //            return Error("角色不存在，请检查");
        //        }

        //        var wards = await _wardRepository.FindAllAsync(m => input.Ids.Contains(m.Id));//role.OrganizationId == m.OrganizationId && 

        //        var roleWards = new List<RoleWardEntity>();
        //        foreach (var ward in wards)
        //        {
        //            var roleWard = new RoleWardEntity
        //            {
        //                Id = Snowflake.GetNewId(),
        //                RoleId = role.Id,
        //                WardId = ward.Id,
        //                OrganizationId = ward.OrganizationId,
        //            };
        //            roleWards.Add(roleWard);
        //        }

        //        await roleWardRepository.RemoveAsync(rp => rp.RoleId == role.Id);
        //        if (roleWards.Any())
        //        {
        //            await roleWardRepository.CreateAsync(roleWards);
        //        }
        //        _unitOfWork.CommitTran();

        //        return Success();
        //    }
        //    catch (Exception)
        //    {
        //        _unitOfWork.RollbackTran();

        //        throw;
        //    }
        //}

        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResultResponse> PutAsync(string id, [FromBody] RoleInputDto input)
        {
            try
            {
                await _unitOfWork.BeginTranAsync();

                var role = await _roleService.FindByIdAsync(id);
                if (role is null)
                {
                    return Error("未查找到该角色，请重新操作");
                }

                role.Code = input.Code;
                role.Name = input.Name;
                role.Description = input.Description;
                role.TypeCode = input.TypeCode;
                role.SortCode = input.SortCode;
                role.IsEnable = input.IsEnable;
                role.OrganizationId = input.OrganizationId;
                role.Remark = input.Remark;

                var res = await _roleService.UpdateAsync(role);

                if (input.ResourceIds is not null)
                {
                    var menus = await _menuService.FindAllAsync(m => input.ResourceIds.Contains(m.Id));//role.OrganizationId == m.OrganizationId &&
                    var rolePermissions = new List<RolePermissionEntity>();
                    foreach (var menu in menus)
                    {
                        var rolePermission = new RolePermissionEntity
                        {
                            Id = Snowflake.GetNewId(),
                            RoleType = 1,
                            RoleId = role.Id,
                            ResourceId = menu.Id,
                            ResourceType = menu.MenuType,
                            OrganizationId = role.OrganizationId,
                            IsEnable = true,
                        };
                        rolePermissions.Add(rolePermission);
                    }

                    var t = new List<int?> { BusinessFunction.rt_0, BusinessFunction.rt_1, BusinessFunction.rt_2, BusinessFunction.rt_3 };
                    await _rolePermissionService.RemoveAsync(rp => rp.RoleId == role.Id && t.Contains(rp.ResourceType));
                    if (rolePermissions.Any())
                    {
                        await _rolePermissionService.CreateAsync(rolePermissions);
                    }
                }

                await _unitOfWork.CommitTranAsync();

                return res > 0 ? Success() : Error();
            }
            catch (Exception ex)
            {
                await _unitOfWork.RollbackTranAsync();

                throw;
            }
        }

        /// <summary>
        ///角色删除
        /// </summary>
        /// <param name="ids">主键集合</param>
        /// <returns></returns>
        [HttpDelete("")]
        public async Task<ResultResponse> DeleteAsync([FromBody] List<string> ids)
        {
            try
            {
                var roles = await _roleService.FindAllAsync(x => ids.Contains(x.Id));

                foreach (var role in roles)
                {
                    if (role.TypeCode == BusinessFunction.TopParentId)
                    {
                        return Error("超级管理员禁止删除");
                    }
                }

                await _unitOfWork.BeginTranAsync();
                var res = await _roleService.RemoveAsync(a => ids.Contains(a.Id));


                //删除菜单权限
                await _rolePermissionService.RemoveAsync(rp => ids.Contains(rp.RoleId));

                await _unitOfWork.CommitTranAsync();

                return res > 0 ? Success() : Error();
            }
            catch
            {
                await _unitOfWork.RollbackTranAsync();
                throw;
            }

        }

        /// <summary>
        /// 角色列表数据
        /// </summary>
        /// <param name="pager">分页</param>
        /// <param name="filter">查询实体参数请求</param>
        /// <returns></returns>
        [HttpGet("")]
        public async Task<ResultResponse<IPagedList<RoleOutputByPageDto>>> GetRolesByPageAsync([FromQuery] PageParam pager, [FromQuery] RoleFilterDto filter)
        {
            var filterData = new RoleFilter();
            if (filter != null)
            {
                filterData.Keyword = filter.Keyword;
                filterData.Code = filter.Code;
                filterData.Name = filter.Name;
                filterData.OrganizationId = filter.OrganizationId;
                filterData.Status = filter.Status;
            }

            var dics = await _keyValueService.GetKeyValueChildByCodeListAsync(BusinessFunction.RoleTypeKey);

            var pagedList = await _roleService.GetRolesByPageAsync(pager, filterData.TrimAll());
            IPagedList<RoleOutputByPageDto> data = new PagedList<RoleOutputByPageDto>()
            {
                PageIndex = pagedList.PageIndex,
                PageSize = pagedList.PageSize,
                TotalCount = pagedList.TotalCount,
                Entities = pagedList.Entities.Select(x => new RoleOutputByPageDto
                {
                    Id = x.Id,
                    Code = x.Code,
                    Name = x.Name,
                    Description = x.Description,
                    TypeCode = x.TypeCode,
                    TypeCodeString = x.TypeCode == BusinessFunction.TopParentId ? "超级管理员" : x.RoleType?.Name,
                    IsEnable = x.IsEnable,
                    OrganizationId = x.OrganizationId,
                    CreatedBy = x.CreatedBy,
                    CreatedTime = x.CreatedTime
                }).ToList()
            };

            var orgIds = data.Entities.Select(m => m.OrganizationId).Distinct().ToList();
            var orgs = await _organizationService.FindAllAsync(o => orgIds.Contains(o.Id));
            foreach (var map in data.Entities)
            {
                var org = orgs.FirstOrDefault(o => o.Id == map.OrganizationId);
                if (org != null)
                {
                    map.OrganizationName = org.Name;
                    map.FullOrganizationName = map.TypeCode == BusinessFunction.TopParentId ? "超级管理员机构" : await _organizationService.GetFullOrgName(map.OrganizationId);
                }
            }

            return Success(data);
        }

        ///// <summary>
        ///// 获取角色病区权限
        ///// </summary>
        ///// <param name="roleId"></param>
        ///// <returns></returns>
        //[HttpGet("resources/roleWards/{roleId}")]
        //public async Task<ResultResponse<List<string>>> GetRoleWards(string? roleId = "")
        //{
        //    if (string.IsNullOrWhiteSpace(roleId))
        //    {
        //        return Error<List<string>>("没有角色Id");
        //    }

        //    var data = await roleWardRepository.FindAllAsync(x => x.RoleId == roleId);
        //    var res = data.Select(x => x.WardId).ToList();

        //    return Success(res);
        //}

        ///// <summary>
        ///// 获取当前登录的病区权限
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet("resources/roleWards")]
        //public async Task<ResultResponse<IList<WardOutputDto>>> GetRoleWardsByLogin()
        //{
        //    if (string.IsNullOrWhiteSpace(LoginDto.RoleId))
        //    {
        //        return Error<IList<WardOutputDto>>("没有角色Id");
        //    }


        //    var rwds = await roleWardRepository.FindAllAsync(x => x.RoleId == LoginDto.RoleId);

        //    var wards = await _wardRepository.FindAllAsync(x => rwds.Select(r => r.WardId).Contains(x.Id));

        //    var res = wards.Adapt<IList<WardOutputDto>>();

        //    return Success(res);
        //}

        ///// <summary>
        ///// 权限树视图数据接口
        ///// </summary>
        ///// <param name="roleId"></param>
        ///// <param name="organizationId"></param>
        ///// <returns></returns>
        //[HttpGet("resources/tree")]
        //public async Task<ResultResponse<List<RolePermissionOutputDto>>> GetPermissionXTree(string roleId = "", string organizationId = "")
        //{
        //    var result = new ResultResponse<List<RolePermissionOutputDto>> { IsSucceed = true };
        //    if (string.IsNullOrWhiteSpace(roleId))
        //    {
        //        return Error<List<RolePermissionOutputDto>>("角色Id不能为空");
        //    }

        //    Expression<Func<MenuEntity, bool>> expression = m => true;
        //    if (!string.IsNullOrWhiteSpace(organizationId))
        //    {
        //        organizationId = organizationId.Trim();
        //        expression = expression.And(m => organizationId == m.OrganizationId);
        //    }

        //    var moduledata = await _menuService.FindAllAsync(expression);
        //    var authorizedata = new List<RolePermissionEntity>();
        //    if (!string.IsNullOrWhiteSpace(roleId))
        //    {
        //        authorizedata = (await _rolePermissionService.FindAllAsync(x => x.RoleId.Equals(roleId))).ToList();
        //    }
        //    //var treeList = new List<XTreeViewModel>();
        //    //foreach (var item in moduledata)
        //    //{
        //    //    var tree = new XTreeViewModel
        //    //    {
        //    //        value = item.Id,
        //    //        title = item.Name,
        //    //        code = item.Code,
        //    //        parentId = item.ParentId,
        //    //        @checked = authorizedata.Any(t => t.ResourceId == item.Id),
        //    //        root = item.Route,
        //    //        icon = item.Icon,
        //    //        sortCode = item.SortCode
        //    //    };
        //    //    treeList.Add(tree);
        //    //}
        //    //treeList = treeList
        //    //    .OrderBy(t => t.sortCode)
        //    //    .ToList();

        //    result.Msg = "查询成功";
        //    result.Data = moduledata.Adapt<List<RolePermissionOutputDto>>();
        //    return result;
        //}

        /// <summary>
        /// 权限树视图数据接口
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}/resources")]
        public async Task<ResultResponse<IEnumerable<RolePermissionOutputDto>>> GetPermissions(string id)
        {
            var result = new ResultResponse<IEnumerable<RolePermissionOutputDto>> { IsSucceed = true };
            if (string.IsNullOrWhiteSpace(id))
            {
                result.IsSucceed = false;
                result.Msg = "没有角色Id";
                return await Task.FromResult(result);
            }

            var permissions = await _rolePermissionService.FindAllAsync(x => x.RoleId.Equals(id));
            var menuIds = permissions.Select(x => x.ResourceId).ToList();
            var menus = await _menuService.FindAllAsync(m => m.Status && menuIds.Contains(m.Id));

            result.Msg = "查询成功";
            result.Data = menus.Adapt<List<RolePermissionOutputDto>>();
            return result;
        }

        /// <summary>
        /// 权限树视图数据接口(当前登录用户)
        /// </summary>
        /// <returns></returns>
        [HttpGet("resources")]
        public async Task<ResultResponse<IEnumerable<RolePermissionOutputDto>>> GetPermissions()
        {
            var result = new ResultResponse<IEnumerable<RolePermissionOutputDto>> { IsSucceed = true };
            var id = LoginDto?.RoleId;
            if (string.IsNullOrWhiteSpace(id))
            {
                result.IsSucceed = false;
                result.Msg = "没有角色Id";
                return await Task.FromResult(result);
            }

            var exp = Expressionable.Create<RolePermissionEntity>();

            var menuIds = new List<string>();
            if (LoginDto?.IsAdmin == false)
            {
                var permissions = await _rolePermissionService.FindAllAsync(x => x.RoleId.Equals(id));

                menuIds = permissions.Select(x => x.ResourceId).ToList();
            }
            else
            {
                menuIds = (await _menuService.FindAllAsync()).Select(x => x.Id).ToList();
            }

            var menus = await _menuService.FindAllAsync(m => m.Status && menuIds.Contains(m.Id));

            result.Msg = "查询成功";
            result.Data = menus.Adapt<List<RolePermissionOutputDto>>().OrderByDescending(d => d.SortCode).ToList();
            return result;
        }

        /// <summary>
        /// 权限树视图数据接口(菜单Ids)(配置树菜单回显)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}/resourceIds")]
        public async Task<ResultResponse<IEnumerable<string>>> GetPermissionIds(string id)
        {
            var result = new ResultResponse<IEnumerable<string>> { IsSucceed = true };
            if (string.IsNullOrWhiteSpace(id))
            {
                result.IsSucceed = false;
                result.Msg = "没有角色Id";
                return await Task.FromResult(result);
            }

            var permissions = await _rolePermissionService.FindAllAsync(x => x.RoleId.Equals(id));
            var menuIds = permissions.Select(x => x.ResourceId).ToList();
            var menus = await _menuService.FindAllAsync(m => m.Status && menuIds.Contains(m.Id));

            result.Msg = "查询成功";
            result.Data = menus.Select(m => m.Id).ToList();
            return result;
        }

        /// <summary>
        /// 权限树视图数据接口(菜单Ids)(配置树菜单回显)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}/resourceIdsAll")]
        public async Task<ResultResponse<object>> GetPermissionIdsAll(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return Error<object>("没有角色Id");
            }

            var menuTypes = new List<int?> { BusinessFunction.rt_0, BusinessFunction.rt_1, BusinessFunction.rt_2, BusinessFunction.rt_3, };
            var mapTypes = new List<int?> { BusinessFunction.rt_100, BusinessFunction.rt_200 };
            var warnTypes = new List<int?> { BusinessFunction.rt_300 };

            var permissions = await _rolePermissionService.FindAllAsync(x => x.RoleId.Equals(id));

            var menuIds = permissions.Where(x => menuTypes.Contains(x.ResourceType)).Select(x => x.ResourceId).ToList();
            var menus = await _menuService.FindAllAsync(m => m.Status && menuIds.Contains(m.Id));



            var warnCodes = permissions.Where(x => warnTypes.Contains(x.ResourceType)).Select(x => x.ResourceId).ToList();
            var warnKeys = await _keyValueService.FindAllAsync(m => m.IsEnable && warnCodes.Contains(m.Code));


            var res = new
            {
                MenuIds = menus.Select(m => m.Id).ToList(),
                WarnTypeCodes = warnKeys.Select(m => m.Code).ToList(),
            };

            return Success<object>(res);
        }

        /// <summary>
        /// 角色下拉列表数据
        /// </summary>
        /// <param name="organizationId"></param>
        /// <returns></returns>
        [HttpGet("select")]
        public async Task<ResultResponse<IList<OutputBySelectDto>>> GetRolesBySelectAsync([FromQuery] string organizationId)
        {
            Expression<Func<RoleEntity, bool>> expression = r => r.IsEnable;
            if (!string.IsNullOrWhiteSpace(organizationId))
            {
                organizationId = organizationId.Trim();
                expression = expression.And(r => organizationId == r.OrganizationId);
            }

            var list = await _roleService.FindAllAsync(expression);

            IList<OutputBySelectDto> res = list.Select(o => new OutputBySelectDto
            {
                Id = o.Id,
                Name = o.Name,
            }).ToList();

            return Success(res);

        }

        /// <summary>
        /// 获取登录用户权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("getPermCode")]
        public async Task<ResultResponse<object>> GetPermCode()
        {
            var roleId = LoginDto?.RoleId;
            if (string.IsNullOrWhiteSpace(roleId))
            {
                return Error<object>("没有角色Id");
            }

            var menuIds = new List<string>();
            if (LoginDto?.IsAdmin == false)
            {
                var permissions = await _rolePermissionService.FindAllAsync(x => x.RoleId.Equals(roleId));

                menuIds = permissions.Select(x => x.ResourceId).ToList();
            }
            else
            {
                menuIds = (await _menuService.FindAllAsync(x => x.Status)).Select(x => x.Id).ToList();
            }

            var allAuth = await _menuService.GetAllAuthAsync();

            var auth = allAuth.Where(x => menuIds.Contains(x.Id));

            var codeList = auth.Select(x => x.Action);

            return Success<object>(new
            {
                allAuth,
                auth,
                codeList
            });
        }

        /// <summary>
        /// 权限树视图数据接口(当前登录用户_左侧菜单)
        /// </summary>
        /// <returns></returns>
        [HttpGet("permissions/resources")]
        public async Task<ResultResponse<IList<MenuOutputDto>>> GetUserPermissions()
        {
            var result = new ResultResponse<IEnumerable<MenuOutputDto>> { IsSucceed = true };
            var id = LoginDto?.RoleId;
            if (string.IsNullOrWhiteSpace(id))
            {
                return Error<IList<MenuOutputDto>>("没有角色Id");
            }

            var menuIds = new List<string>();
            if (LoginDto?.IsAdmin == false)
            {
                var t = new List<int?> { BusinessFunction.rt_0, BusinessFunction.rt_1, BusinessFunction.rt_2, BusinessFunction.rt_3, };
                var permissions = await _rolePermissionService.FindAllAsync(x => x.RoleId.Equals(id) && t.Contains(x.ResourceType));

                menuIds = permissions.Select(x => x.ResourceId).ToList();
            }
            else
            {
                menuIds = (await _menuService.FindAllAsync()).Select(x => x.Id).ToList();
            }


            //只返回主菜单和子菜单
            var mts = new List<int?> { BusinessFunction.rt_0, BusinessFunction.rt_1, };

            var menus = await _menuService.GetMenusAsync(m => m.Status && menuIds.Contains(m.Id) && mts.Contains(m.MenuType));

            return Success(menus);
        }


        /// <summary>
        /// 菜单列表（角色页面用）
        /// </summary>
        /// <param name="parentId">查询实体参数请求</param>
        /// <returns></returns>
        [HttpGet("RoleMenuTrees")]
        public async Task<ResultResponse<IList<MenuOutputDto>>> GetMenusByRoleTreesAsync()
        {
            var id = LoginDto?.RoleId;
            if (string.IsNullOrWhiteSpace(id))
            {
                return Error<IList<MenuOutputDto>>("没有角色Id");
            }

            var menuIds = new List<string>();
            if (LoginDto?.IsAdmin == false)
            {
                var t = new List<int?> { BusinessFunction.rt_0, BusinessFunction.rt_1, BusinessFunction.rt_2, BusinessFunction.rt_3, };
                var permissions = await _rolePermissionService.FindAllAsync(x => x.RoleId.Equals(id) && t.Contains(x.ResourceType));

                menuIds = permissions.Select(x => x.ResourceId).ToList();
            }
            else
            {
                menuIds = (await _menuService.FindAllAsync()).Select(x => x.Id).ToList();
            }

            var data = await _menuService.GetMenusAsync(x => menuIds.Contains(x.Id) && x.Status);

            return Success(data);
        }


        /// <summary>
        /// 菜单列表数据（根据父级路径获取）
        /// </summary>
        /// <param name="parentUrl">查询实体参数请求</param>
        /// <returns></returns>
        [HttpGet("RoleMenuTreesParentUrl")]
        public async Task<ResultResponse<IList<MenuOutputDto>>> GetMenusByTreeWithParentPathAsync([FromQuery] string parentUrl)
        {
            var menu = await _menuService.FirstOrDefaultAsync(o => o.Url == parentUrl);

            if (menu is null)
            {
                return Error<IList<MenuOutputDto>>("此路径无对应菜单配置，请检查");
            }

            var data = (await _menuService.FindAllAsync(o => o.ParentId == menu.Id && o.Status)).Adapt<IList<MenuOutputDto>>();

            var id = LoginDto?.RoleId;
            if (string.IsNullOrWhiteSpace(id))
            {
                return Error<IList<MenuOutputDto>>("没有角色Id");
            }


            if (LoginDto?.IsAdmin == false)
            {
                var t = new List<int?> { BusinessFunction.rt_0, BusinessFunction.rt_1, BusinessFunction.rt_2, BusinessFunction.rt_3, };

                var permissions = await _rolePermissionService.FindAllAsync(x => x.RoleId.Equals(id) && t.Contains(x.ResourceType));

                var menuIds = permissions.Select(x => x.ResourceId).ToList();

                data = data.Where(x => menuIds.Contains(x.Id)).ToList();
            }

            return Success(data);
        }
    }
}